package com.leo.ktvplayer.ui.playing;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.widget.TextView;

import com.leo.ktvplayer.R;
import com.leo.ktvplayer.base.ActBase;
import com.leo.ktvplayer.bluetooth.BleConstant;
import com.leo.ktvplayer.bluetooth.bletask.BleEngineFactory;
import com.leo.ktvplayer.bluetooth.bletask.IBleDataEngine;
import com.leo.ktvplayer.ui.chosetype.ActChoseType;
import com.leo.ktvplayer.ui.payment.ActPayment;
import com.leo.ktvplayer.util.TimeFormatUtil;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 *
 */
public class ActPlaying extends ActBase {

    private TimeCounter counter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playing);
        ButterKnife.bind(this);
        startCounter();
        tv_showFinish.setText("正在唱歌中,请秀出您的歌喉吧~");
    }

    /**
     * 启动定时器
     */
    public void startCounter(){
        int time = getIntent().getIntExtra(TAG_PLAY_TIME,-1);
        counter = new TimeCounter(1000,time);
        counter.setOnTimeFinishCallback(() -> {
            tv_showCounter.setText("00:00");
            tv_showFinish.setText("时间已到,欢迎下次再玩~");
            handler.postDelayed(() -> {
                IBleDataEngine engine =  BleEngineFactory.getInstance(BleConstant.KEY_FOR_LOCK_DEVICE);
                engine.excuteData();//锁住房间

                IBleDataEngine voice = BleEngineFactory.getInstance(BleConstant.KEY_FOR_UPDATE_DEVICE_AUDIO);
                voice.excuteData();

                IBleDataEngine mic = BleEngineFactory.getInstance(BleConstant.KEY_FOR_UPDATE_MIC_AUDIO);
                mic.excuteData();

                goToChoosType();
            },5000);
        });
        counter.setOnTimerTickCallBack((tickTime -> {
            tv_showCounter.setText(TimeFormatUtil.formatMinAndSecend(tickTime));
        }));
        counter.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        counter.cancel();
    }

    /**
     * 跳转到选择类型的页面
     */
    private void goToChoosType(){
        Intent intent = new Intent();
        intent.setClass(this, ActChoseType.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @BindView(R.id.tv_showfinish)
    public TextView tv_showFinish;
    @BindView(R.id.tv_counter)
    public TextView tv_showCounter;

    private Handler handler = new Handler();

    public static final String TAG_PLAY_TIME = "com.leo.ktyplay.TAG_PLAY_TIME";
}
